package mysql

func genWork(presifx string, tabname string, packageName string) string {
	retStr := ""
	retErr := ""
	retLast := ""
	tmpStr := ""
	paramList := ""
	typeName := underlineToUpper(tabname) + suffix
	if presifx == "Insert" {
		retStr = "(int64, error)"
		retErr = " 0,err "
		retLast = " id, nil "
		tmpStr = "id, err := " + packageName + "."
		paramList = "(d *" + packageName + "." + typeName + ") "
	} else {
		retStr = " error "
		retErr = " err "
		retLast = " nil "
		tmpStr = " err := " + packageName + "."
		paramList = "(d *" + packageName + "." + typeName + ") "
	}

	con := "func " + presifx + underlineToUpper(tabname) + paramList + retStr + " {\r\n" +
		`if d == nil {
		lg.ELogger.Println("param nil")
		err := errors.New("param nil")
		return ` + retErr + "\r\n}\r\n" +
		tmpStr + presifx + underlineToUpper(tabname) + "(*d, db)\r\n" +
		`if err != nil {
		return ` + retErr + "\r\n}\r\n\r\nreturn" + retLast + "\r\n}\r\n"

	if presifx == "Select" {
		con = "func " + presifx + underlineToUpper(tabname) + "(id int64) (*" + packageName + "." + typeName + ",error) {\r\n" +
			"r, err := " + packageName + "." + presifx + underlineToUpper(tabname) + "(id,db)\r\n" +
			"return r,err\r\n}\r\n"
	}

	return con
}
func genWorkInserts(tabname string, packageName string) string {
	typeName := underlineToUpper(tabname) + suffix

	con := "func Inserts" + underlineToUpper(tabname) + "(ds []" + packageName + "." + typeName + ") error {\r\n" +
		"err := " + packageName + ".Inserts" + underlineToUpper(tabname) + "(ds, db)\r\n" +
		"return err\r\n}\r\n"
	return con
}

/*
type FloorsData struct {
	Data  []ud.PgFloorData `json:"data"`
	Total int              `json:"total"`
}
*/
// func genWorkDatas(keys [][]string, tabname, packageName string) string {
// 	con := "func " + tabname + "sData struct {\r\n" +
// 		"Data []ud." + underlineToUpper(tabname) + suffix + "`json:\"data\"`\r\n"
// }

func genWorkContent(head string, body string, packageName string) (string, string, string) {
	tabname := parseTableName(head)
	keys := parseKey(body)
	// log.Println("tabname:", tabname)
	// log.Println("keys:", keys)
	if len(tabname) <= 0 || keys == nil {
		return "", "", ""
	}

	icon := genWork("Insert", tabname, packageName)
	ucon := genWork("Update", tabname, packageName)
	dcon := genWork("Delete", tabname, packageName)
	sdcon := genWork("SoftDelete", tabname, packageName)
	sedcon := genWork("Select", tabname, packageName)
	inserts := genWorkInserts(tabname, packageName)
	dcon = dcon + sdcon + sedcon + inserts

	return icon, ucon, dcon
}
